package com.mcb_wxc.util;

import java.io.*;
import java.util.Properties;

/**
 * Created by 小生
 * 2019/1/17 20:16.
 */
public class PropertiesUtil {
    /**
     * 根据KEY，读取文件对应的值
     * @param fileName 文件完整名称，例如：accessToken.properties
     * @param key 键
     * @return key对应的值
     */
    private static String resourcesUrl = System.getProperty("user.dir")+"/mcb_wxc/src/main/resources/";
    public static String readData(String fileName, String key) {
        System.out.println(resourcesUrl);
        //获取绝对路径
        fileName = resourcesUrl+fileName;
        fileName = fileName.replace("\\","/");
        Properties props = new Properties();
        try {
            InputStream in = new BufferedInputStream(new FileInputStream(fileName));
            props.load(in);
            in.close();
            String value = props.getProperty(key);
            if(value != null) { //不为空就设置编码
                value = new String(value.getBytes("ISO-8859-1"), "utf-8");
            }
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 修改或添加键值对 如果key存在，修改, 反之，添加。
     * @param fileName 文件完整名称，例如：accessToken.properties
     * @param key 键
     * @param value 键对应的值
     */
    public static void writeData(String fileName, String key, String value) {
        //获取绝对路径
        fileName = resourcesUrl+fileName;
        fileName = fileName.replace("\\","/");
        Properties prop = new Properties();
        try {
            File file = new File(fileName);
            if (!file.exists())
                file.createNewFile();
            InputStream fis = new FileInputStream(file);
            prop.load(fis);
            //一定要在修改值之前关闭fis
            fis.close();
            OutputStream fos = new FileOutputStream(fileName);
            prop.setProperty(key, value);
            //保存，并加入注释
            prop.store(new OutputStreamWriter(fos, "utf-8"), "Update '" + key + "' value");
            fos.close();
        } catch (IOException e) {
            System.err.println("Visit " + fileName + " for updating " + value + " value error");
        }
    }

    public static void main(String[] args) {
        //修改 获取 添加
        PropertiesUtil.writeData("accessToken.properties", "accessToken","嗯哼");
        //读取
        String val = PropertiesUtil.readData("accessToken.properties", "accessToken");
        System.out.println(val);
    }
}
